<template>
  <div>
    <el-button type="primary" @click="showAddModal">添加</el-button>
    <el-table ref="multipleTableRef" :data="tableData" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column property="ProCode" label="生产单号" width="120" />
      <el-table-column property="ProDate" label="单据日期" width="120">
        <template #default="scope">
          {{ scope.row.ProDate.substr(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column property="ProPeo" label="负责人" width="120" />
      <el-table-column property="ProPhone" label="联系电话" width="120" />
      <el-table-column property="ProPeople" label="生产人员" width="120" />
      <el-table-column property="ProDesc" label="备注" width="120" />
      <el-table-column property="ProDateInfo" label="生产日期" width="120">
        <template #default="scope">
          {{ scope.row.ProDateInfo.substr(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <a href="#" @click="handleView(scope.row.ProId)" style="color: blue">查看</a>
          <el-link href="#" @click="(drawer = true), GetProduce(scope.row.ProId)" style="color: green">编辑</el-link>
          <el-link type="danger" @click="handleDelete(scope.row.ProId)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="pagination.pageIndex" :page-sizes="[10, 20, 30, 40]" :page-size="pagination.pageSize"
      :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
    <el-drawer v-model="drawer" title="Edit" size="80%">
      <div class="about" style="width: 1200px; margin: auto">
        <h4 style="text-align: left; font-weight: bold">基础信息</h4>
        <br />
        <el-form ref="ruleFormRef" style="max-width: 1300px; width: 1100px; margin: auto" :model="ruleForm"
          :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="生产单号" prop="proCode">
                <el-input v-model="ruleForm.proCode" :disabled="isDisabled" />
                <el-checkbox v-model="systemNumber" @change="generateSystemNumber" value="Online activities" name="type"
                  :disabled="isDisabled">系统编号</el-checkbox>
              </el-form-item>
              <el-form-item label="负责人" prop="proPeo">
                <el-input v-model="ruleForm.proPeo" />
              </el-form-item>
              <el-form-item label="生产人员" prop="proPeople">
                <el-input v-model="ruleForm.proPeople" />
              </el-form-item>
              <el-form-item label="生产日期" prop="proDateInfo">
                <el-date-picker v-model="ruleForm.proDateInfo" type="date" label="Pick a date" placeholder="生产日期"
                  style="width: 100%" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="单据日期" prop="proDate">
                <el-date-picker v-model="ruleForm.proDate" type="date" label="Pick a date" placeholder="单据日期"
                  style="width: 100%" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
              </el-form-item>
              <el-form-item label="联系电话" prop="proPhone">
                <el-input v-model.number="ruleForm.proPhone" maxlength="11" show-word-limit />
              </el-form-item>
              <el-form-item label="备注" prop="proDesc">
                <el-input v-model="ruleForm.proDesc" type="textarea" maxlength="200" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <br />
        <br />
        <p style="text-align: center">
          <el-button type="primary" @click="handleEdit(ruleFormRef)">
            修改
          </el-button>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <el-button @click="drawer = false">取消</el-button>
        </p>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import {
  ElTable,
  ElPagination,
  ElButton,
  ElMessageBox,
  ElMessage,
} from "element-plus";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
const isDisabled = ref(true);
interface RuleForm {
  proId: number;
  proCode: string;
  proDate: string;
  proPeo: string;
  proPhone: string;
  proPeople: string;
  proDesc: string;
  proDateInfo: string;
}

const router = useRouter();
const route = useRoute();
const drawer = ref(false);
const systemNumber = ref(false);
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  proId: 0,
  proCode: "",
  proDate: "",
  proPeo: "",
  proPhone: "",
  proPeople: "",
  proDesc: "",
  proDateInfo: "",
});
// interface Product {
//   ProId: number;
//   ProCode: string;
//   ProDate: string;
//   ProPeo: string;
//   ProPhone: string;
//   ProPeople: string;
//   ProDesc: string;
//   ProDateInfo: string;
// }

const rules = reactive<FormRules<RuleForm>>({
  proCode: [
    {
      required: true,
      message: "请选择生产单号",
      trigger: "change",
    },
    { min: 2, max: 20, message: "长度在2到20之间", trigger: "blur" },
  ],
  proDate: [
    {
      required: true,
      message: "请选择单据日期",
      trigger: "change",
    },
  ],
  proPeo: [
    {
      required: true,
      message: "请输入负责人",
      trigger: "change",
    },
  ],
  proPhone: [
    {
      required: true,
      message: "请输入联系电话",
      trigger: "change",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "联系电话格式不正确",
    },
  ],
  proPeople: [
    {
      required: true,
      message: "请输入生产人员",
      trigger: "change",
    },
  ],
  proDesc: [
    {
      required: true,
      message: "请输入备注",
      trigger: "change",
    },
    { min: 10, max: 200, message: "长度在10到200之间", trigger: "blur" },
  ],
  proDateInfo: [
    {
      required: true,
      message: "请选择生产日期",
      trigger: "change",
    },
  ],
});

const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const tableData = ref<Product[]>([]);
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});

const fetchData = async () => {
  try {
    const response = await axios.get(
      `Produce/GetProduceShow?pageIndex=${pagination.pageIndex}&pageSize=${pagination.pageSize}`
    );
    const data = response.data;
    tableData.value = data.Data;
    pagination.total = data.TotalCount;
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};

import { formatDate } from "../production(生产管理)/filter.js";
const generateSystemNumber = () => {
  if (systemNumber.value) {
    ruleForm.proCode = "CG-" + formatDate(new Date(), "yyyymdhs");
  } else {
    ruleForm.proCode = "";
  }
};

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchData();
};

const handleCurrentChange = (val: number) => {
  pagination.pageIndex = val;
  fetchData();
};

const showAddModal = () => {
  router.push(`/UserList/production`);
};

const handleEdit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      axios.put("Produce/UpdateProduce", ruleForm).then((res) => {
        if (res.data > 0) {
          ElMessage.success("修改成功！");
          drawer.value = false;
          fetchData();
        } else {
          ElMessage.error("修改失败！");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const handleDelete = (ProId: string) => {
  ElMessageBox.confirm("确认要删除吗?", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    axios.delete(`Produce/DelteProduce?ProId=${ProId}`).then((res) => {
      if (res.data > 0) {
        ElMessage.success("删除成功！");
        fetchData();
      }
    });
  });
};

const GetProduce = (ProId: string) => {
  //   const ProId = route.query.ProId;
  axios.get(`Produce/GetProduceByProId?ProId=${ProId}`).then((res) => {
    const ProduceList = res.data;
    (ruleForm.proId = ProduceList.ProId),
      (ruleForm.proCode = ProduceList.ProCode),
      (ruleForm.proDate = ProduceList.ProDate),
      (ruleForm.proPeo = ProduceList.ProPeo),
      (ruleForm.proPhone = ProduceList.ProPhone),
      (ruleForm.proPeople = ProduceList.ProPeople),
      (ruleForm.proDesc = ProduceList.ProDesc),
      (ruleForm.proDateInfo = ProduceList.ProDateInfo);
  });
};

const handleView = (ProId: string) => {
  router.push(`/UserList/productionDesc?ProId=${ProId}`);
};

onMounted(fetchData);
GetProduce("0");
</script>
